package com.objectcarpentry.kaylee.ui.controls;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

public class SlickVolumeControl implements PaintListener, Listener {
	
	private double volume = 1;
	private Canvas canvas;
	
	public SlickVolumeControl(Composite c) {
		canvas = new Canvas(c, SWT.NONE);
		canvas.addPaintListener(this);
		canvas.addListener(SWT.MouseDown, this);
		canvas.addListener(SWT.MouseMove, this);
	}

	@Override
	public void paintControl(PaintEvent e) {
		
		Rectangle clientArea = canvas.getClientArea();
        int width = clientArea.width;
        int height = clientArea.height;
       // e.gc.setClipping(20,20,width - 40, height - 40);
        e.gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_CYAN));
        e.gc.fillPolygon(new int[] {0, height, (int) (volume * width), height , (int) (volume * width),height - (int)(volume * height)}); 
	}

	public Control getControl() {
		return canvas;
	}

	@Override
	public void handleEvent(Event e) {
		boolean mod = false;
		  
		 if ((e.button > 0)) {
			 // this handles the click
			 mod = true;
		 } else {
			 // and this the drag
			 if ((e.stateMask & SWT.BUTTON1) != 0)
				 mod = true;
			 if (!mod && (e.stateMask & SWT.BUTTON2) != 0)
				 mod = true;
			 if (!mod && (e.stateMask & SWT.BUTTON3) != 0)
	          mod = true;
		}
		if (mod) {
			setVolume( (double) e.x / (double) canvas.getClientArea().width);
		}
	}

	private void setVolume(double d) {
		d = Math.max(0, d);
		d = Math.min(1, d);
		volume = d;
		canvas.redraw();
	}

	
	
	
	
}
